{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2023 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# vrp_tokens"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/vrp_tokens.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/vrp_tokens.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Simple VRP with special locations which need to be visited at end of the route.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ortools.constraint_solver import routing_enums_pb2\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "def create_data_model():\n",
    "    \"\"\"Stores the data for the problem.\"\"\"\n",
    "    data = {}\n",
    "    # Special location don't consume token, while regular one consume one\n",
    "    data[\"tokens\"] = [\n",
    "        0,  # 0 depot\n",
    "        0,  # 1 special node\n",
    "        0,  # 2 special node\n",
    "        0,  # 3 special node\n",
    "        0,  # 4 special node\n",
    "        0,  # 5 special node\n",
    "        -1,  # 6\n",
    "        -1,  # 7\n",
    "        -1,  # 8\n",
    "        -1,  # 9\n",
    "        -1,  # 10\n",
    "        -1,  # 11\n",
    "        -1,  # 12\n",
    "        -1,  # 13\n",
    "        -1,  # 14\n",
    "        -1,  # 15\n",
    "        -1,  # 16\n",
    "        -1,  # 17\n",
    "        -1,  # 18\n",
    "    ]\n",
    "    # just need to be big enough, not a limiting factor\n",
    "    data[\"vehicle_tokens\"] = [20, 20, 20, 20]\n",
    "    data[\"num_vehicles\"] = 4\n",
    "    data[\"depot\"] = 0\n",
    "    return data\n",
    "\n",
    "\n",
    "def print_solution(manager, routing, solution):\n",
    "    \"\"\"Prints solution on console.\"\"\"\n",
    "    print(f\"Objective: {solution.ObjectiveValue()}\")\n",
    "    token_dimension = routing.GetDimensionOrDie(\"Token\")\n",
    "    total_distance = 0\n",
    "    total_token = 0\n",
    "    for vehicle_id in range(manager.GetNumberOfVehicles()):\n",
    "        plan_output = f\"Route for vehicle {vehicle_id}:\\n\"\n",
    "        index = routing.Start(vehicle_id)\n",
    "        total_token += solution.Value(token_dimension.CumulVar(index))\n",
    "        route_distance = 0\n",
    "        route_token = 0\n",
    "        while not routing.IsEnd(index):\n",
    "            node_index = manager.IndexToNode(index)\n",
    "            token_var = token_dimension.CumulVar(index)\n",
    "            route_token = solution.Value(token_var)\n",
    "            plan_output += f\" {node_index} Token({route_token}) -> \"\n",
    "            previous_index = index\n",
    "            index = solution.Value(routing.NextVar(index))\n",
    "            route_distance += routing.GetArcCostForVehicle(\n",
    "                previous_index, index, vehicle_id\n",
    "            )\n",
    "        node_index = manager.IndexToNode(index)\n",
    "        token_var = token_dimension.CumulVar(index)\n",
    "        route_token = solution.Value(token_var)\n",
    "        plan_output += f\" {node_index} Token({route_token})\\n\"\n",
    "        plan_output += f\"Distance of the route: {route_distance}m\\n\"\n",
    "        total_distance += route_distance\n",
    "        print(plan_output)\n",
    "    print(f\"Total distance of all routes: {total_distance}m\")\n",
    "    print(f\"Total token of all routes: {total_token}\")\n",
    "\n",
    "\n",
    "def main():\n",
    "    \"\"\"Solve the CVRP problem.\"\"\"\n",
    "    # Instantiate the data problem.\n",
    "    data = create_data_model()\n",
    "\n",
    "    # Create the routing index manager.\n",
    "    manager = pywrapcp.RoutingIndexManager(\n",
    "        len(data[\"tokens\"]), data[\"num_vehicles\"], data[\"depot\"]\n",
    "    )\n",
    "\n",
    "    # Create Routing Model.\n",
    "    routing = pywrapcp.RoutingModel(manager)\n",
    "\n",
    "    # Create and register a transit callback.\n",
    "    def distance_callback(from_index, to_index):\n",
    "        \"\"\"Returns the distance between the two nodes.\"\"\"\n",
    "        del from_index\n",
    "        del to_index\n",
    "        return 10\n",
    "\n",
    "    transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n",
    "\n",
    "    routing.AddDimension(\n",
    "        transit_callback_index,\n",
    "        0,  # null slack\n",
    "        3000,  # maximum distance per vehicle\n",
    "        True,  # start cumul to zero\n",
    "        \"distance\",\n",
    "    )\n",
    "    distance_dimension = routing.GetDimensionOrDie(\"distance\")\n",
    "    distance_dimension.SetGlobalSpanCostCoefficient(100)\n",
    "\n",
    "    # Define cost of each arc.\n",
    "    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
    "\n",
    "    # Add Token constraint.\n",
    "    def token_callback(from_index):\n",
    "        \"\"\"Returns the number of token consumed by the node.\"\"\"\n",
    "        # Convert from routing variable Index to tokens NodeIndex.\n",
    "        from_node = manager.IndexToNode(from_index)\n",
    "        return data[\"tokens\"][from_node]\n",
    "\n",
    "    token_callback_index = routing.RegisterUnaryTransitCallback(token_callback)\n",
    "    routing.AddDimensionWithVehicleCapacity(\n",
    "        token_callback_index,\n",
    "        0,  # null capacity slack\n",
    "        data[\"vehicle_tokens\"],  # vehicle maximum tokens\n",
    "        False,  # start cumul to zero\n",
    "        \"Token\",\n",
    "    )\n",
    "    # Add constraint: special node can only be visited if token remaining is zero\n",
    "    token_dimension = routing.GetDimensionOrDie(\"Token\")\n",
    "    for node in range(1, 6):\n",
    "        index = manager.NodeToIndex(node)\n",
    "        routing.solver().Add(token_dimension.CumulVar(index) == 0)\n",
    "\n",
    "    # Instantiate route start and end times to produce feasible times.\n",
    "    for i in range(manager.GetNumberOfVehicles()):\n",
    "        routing.AddVariableMinimizedByFinalizer(\n",
    "            token_dimension.CumulVar(routing.Start(i))\n",
    "        )\n",
    "        routing.AddVariableMinimizedByFinalizer(\n",
    "            token_dimension.CumulVar(routing.End(i))\n",
    "        )\n",
    "\n",
    "    # Setting first solution heuristic.\n",
    "    search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
    "    search_parameters.first_solution_strategy = (\n",
    "        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC\n",
    "    )\n",
    "    search_parameters.local_search_metaheuristic = (\n",
    "        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH\n",
    "    )\n",
    "    search_parameters.time_limit.FromSeconds(1)\n",
    "\n",
    "    # Solve the problem.\n",
    "    solution = routing.SolveWithParameters(search_parameters)\n",
    "\n",
    "    # Print solution on console.\n",
    "    if solution:\n",
    "        print_solution(manager, routing, solution)\n",
    "    else:\n",
    "        print(\"No solution found !\")\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
